package com.linyu.mallchat.common.websocket;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.linyu.mallchat.common.websocket.domain.enums.WSReqTypeEnum;
import com.linyu.mallchat.common.websocket.domain.vo.req.WSBaseRequest;
import com.linyu.mallchat.common.websocket.service.WebSocketService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import io.netty.channel.ChannelHandler.Sharable;

/**
 * @author 23087
 */
@Slf4j
@Sharable // 共用业务处理器的话，需要标注该注解
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private WebSocketService webSocketService;

    /**
     * 链接建立成功：链接建立成功后，会触发该事件
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        webSocketService = SpringUtil.getBean(WebSocketService.class);
        webSocketService.connect(ctx.channel());
    }

    /**
     * 用户事件触发器
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            log.info("握手完成");
        }else if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
//                System.out.println("读空闲");
                // todo 用户下线（本身，IdleStateHandler 的开启不会强制下线，需要主动编码）
                userOffline(ctx.channel());
            }
        }
    }

    /**
     * 链接断开，调用下线
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        userOffline(ctx.channel());
    }

    /**
     * 用户下线统一处理
     */
    public void userOffline(Channel channel){
        webSocketService.remove(channel);
        channel.close(); // 关闭连接
    }


    /**
     * 消息处理器
     * todo 真正处理业务逻辑的地方
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
//        log.info("收到消息：{}", text);
        WSBaseRequest wsBaseRequest = JSONUtil.toBean(text, WSBaseRequest.class);
        // 下面代码 策略模式 的体现
        switch (WSReqTypeEnum.of(wsBaseRequest.getType())) {
            case LOGIN:
                webSocketService.handleLoginReq(ctx.channel());
                break;
            case HEARTBEAT:
                break;
            case AUTHORIZE:
        }
    }
}
